import type { ProColumns } from '@ant-design/pro-components';
import { Button, Modal, Popconfirm, message, Switch, Table, Space } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { LoadingOutlined } from "@ant-design/icons"
import {
  ProTable,
  PageContainer, TableDropdown,
} from '@ant-design/pro-components';
import IHttp from "@/services/http.service";
import PubTaskCreateForm from "@/pages/Pub/TaskList/PubTaskCreateForm";
import VideoCutTemplateCreateForm from "@/pages/Video/CutTemplate/CutTemplateCreateForm";
import PubAccountSelector from "@/pages/Pub/TaskList/PubAccountSelector";
import BatchAddForm from "@/pages/Pub/TaskList/BatchAddForm";
import {firstValueFrom, map,} from "rxjs";
import IHelper from '@/services/helper.service';

export default function PubTaskListPage() {
  const [pubTaskSettings, setPubTaskSettings] = useState<any>(undefined) 
  const [autoFetchSwitchLoading, setAutoFetchSwitchLoading] = useState<boolean>(false) 
  const [publishingIds, setPublishingIds] = useState<number[]>([])
  const ref = useRef<Ant.ProTableActionType>()
  const [editItem, setEditItem] = useState<API.PubTaskItem | undefined>()
  const [pubAccountSelectorItem, setPubAccountSelectorItem] = useState<API.PubTaskItem | undefined>()
  const [cutConfigTriggerId, setCutConfigTriggerId] = useState<number[]>([])
  const [batchAddItem, setBatchAddItem] = useState<API.PubTaskItem | undefined>()
  const columns: ProColumns<API.PubTaskItem>[] = [
    {
      title: '标题',
      dataIndex: 'title',
      render: (_, record) => <a onClick={() => setEditItem({...record})}>{_}</a>,
    },
    {
      title: '发布状态',
      dataIndex: 'pub_state',
      render: (_, record) => {
        return <Switch value={record.pub_state === 1} onClick={(checked: boolean) => handlePubStateSwitchClick(record.id, checked)}/>
      }
    },
    {
      title: "视频",
      dataIndex: "video",
      render: (_, record) => {
        return (
          <p>
            {(record.video_upload_id || record.video_bili_bvid || "").split("_").shift()}
            <a className='mx-1' onClick={() => preview("video", {...record})}>预览视频</a>
            <a onClick={() => preview("cover", {...record})}>预览封面</a>
          </p>
          
        )
      }
    },
    {
      title: "发布账号",
      dataIndex: "video",
      render: (_, record) => (record.account || "").split(",").map(acc => acc.split("_").shift()).join(",")
    },
    {
      title: '操作',
      key: 'option',
      width: 140,
      valueType: 'option',
      render: (_, record) => [
        <Popconfirm
          key="del"
          title="删除任务"
          description="确定要删除当前任务吗？"
          okText="确定"
          cancelText="取消"

          onConfirm={() => {
            return firstValueFrom(
              IHttp.delPubTask(record.id).pipe(
                map(() => ref.current?.reload())
              )
            )
          }}
        >
          <a className="text-[#ff4d4f]">删除</a>
        </Popconfirm>,
        <TableDropdown
          key="actionGroup"
          onSelect={k => {
            if (k === "get_video") {
              setCutConfigTriggerId([record.id])
            }
            if (k === "publish") {
              // startPubTask(record)
              setPubAccountSelectorItem(record)
            }

            if (k === "copy") {
              copyTask(record)
            }
            if (k === "del_video") {
              delTaskVideo(record)
            }
            if ("batch_add" === k) {
              setBatchAddItem(record)
              // batchAddTask(record)
            }
          }}
          menus={[
            { key: 'get_video', name: '获取视频' },
            { key: 'del_video', name: '删除视频' },
            { key: 'publish', name: '发布' },
            { key: 'copy', name: '复制' },
            { key: 'batch_add', name: '批量添加' },
          ]}
        />,
      ],
    },
  ]

  useEffect(() => {
    getPubTaskSettings()
  }, [])

  function getPubTaskSettings() {
    return IHttp.getPubTaskSettings().subscribe(
      res => {
        if (res.status) {
          setPubTaskSettings(res.data.settings)
        }
      }
    )
  }

  function preview(type: "video" | "cover", task: API.PubTaskItem) {
    const videoId = +((task.video_upload_id || "").split("_").pop() || "")
    if (!videoId) {
      message.error("video id 不存在")
      return
    }
    IHttp.getVideoInfo(videoId).subscribe(
      res => {
        if (!res.status) return
        if (!res.data?.video || !res.data?.cover) {
          message.error("视频或封面不存在")
          return
        }
        Modal.info({
          icon: null,
          closable: true,
          content: (
            <>
              <div className="flex flex-row items-center">
                {type === "video" ? (
                  <video controls src={IHelper.getServerAsset(res.data.video)} autoPlay></video>
                ) : (
                  <img src={IHelper.getServerAsset(res.data.cover)} alt="" />
                )}
              </div>
            </>
          ),
          footer: null
        })
        // console.log(res)
      }
    )
  }

  function openGetVideoQueue() {
    IHttp.getGetVideoQueue().subscribe(
      res => {
        if (!res.status) return
        Modal.info({
          title: `视频处理队列 剩余数量[${res.data.length}]`,
          content: (
            <div className=''>
              <Table
                rowKey={"id"}
                className='h-80 overflow-x-auto' 
                columns={[
                  {title: 'id', dataIndex: 'id',},
                  {title: '标题', dataIndex: 'title',}
                ]}
                dataSource={res.data}
                pagination={false}
              />
              
            </div>
            
          )
        })
      }
    )
  }

  function delTaskVideo(task: API.PubTaskItem) {
    IHttp.updatePubTask(task.id, {video_upload_id: ""}).subscribe(
      res => {
        if (res.status) {
          message.success("删除成功")
          ref.current?.reload()
        }
      }
    )
  }
  function getTaskVideo(taskId: number[], config: any) {
    const closeLoading = message.loading(`${taskId} 正在获取视频`, 0)
    IHttp.getTaskVideoAsync(taskId, config).subscribe(
      res => {
        closeLoading()
        if (!res.status) {
          return
        }
        message.success(res.message || "获取成功")
        ref.current?.reload()
      }
    )
  }

  async function startPubTask(task: API.PubTaskItem, select_accounts: string) {
    let res = await firstValueFrom(IHttp.startPubTask(task?.id as number, select_accounts || undefined))
    if (res.status) {
      message.success("开始发布")
    }
    setPubAccountSelectorItem(undefined)
    return true
  }

  function copyTask(task: API.PubTaskItem) {
    IHttp.copyPubTask(task.id).subscribe(
      res => {
        if (!res.status) return
        ref.current?.reload()
      }
    )
  }

  function handleAutoFetchSwitchClick(checked: boolean) {
    setAutoFetchSwitchLoading(true)
    let nextSettings = {...pubTaskSettings, autoFetch: checked ? 1 : 0}
    IHttp.setPubTaskSettings(nextSettings).subscribe(
      res => {
        setAutoFetchSwitchLoading(false)
        if (res.status) {
          setPubTaskSettings(res.data.settings)
        }
      }
    )
  }

  function handlePubStateSwitchClick(id: number, checked: boolean) {
    IHttp.updatePubTask(id, {pub_state: checked ? 1 : 0}).subscribe(
      res => {
        if (res.status) {
          ref.current?.reload()
        }
      }
    )
  }

  const pageContent = (
    <>
      自动获取视频 
      <Switch 
        className='ml-2'
        loading={autoFetchSwitchLoading}
        value={pubTaskSettings?.autoFetch === 1}
        onClick={handleAutoFetchSwitchClick}
      />
    </>
  )
 
  return (
    <>
      <PageContainer
        content={pageContent}
      >
        <ProTable<API.PubTaskItem>
          // @ts-ignore
          actionRef={ref}
          columns={columns}
          rowClassName={(record: API.PubTaskItem) => record.pub_state === 1 ? "bg-slate-200" : ""}
          request={(params, sorter, filter) => {
            // 表单搜索项会从 params 传入，传递给后端接口。
            // console.log(params, sorter, filter);
            return firstValueFrom(
              IHttp.getPubTaskList({page: params.current, pageSize: params.pageSize}).pipe(
                map(res => {
                  return {
                    data: res.data.list,
                    // success 请返回 true，
                    // 不然 table 会停止解析数据，即使有数据
                    success: true,
                    // 不传会使用 data 的长度，如果是分页一定要传
                    total: res.data.total,
                  }
                })
              )
            )
          }}
          rowSelection={{
            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
            // 注释该行则默认不显示下拉选项
            selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
            defaultSelectedRowKeys: [],
          }}
          tableAlertRender={({
            selectedRowKeys,
            selectedRows,
            onCleanSelected,
          }) => {
            return (
              <Space size={24}>
                <span>
                  已选 {selectedRowKeys.length} 项
                  <a style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
                    取消选择
                  </a>
                </span>
              </Space>
            );
          }}
          tableAlertOptionRender={({selectedRowKeys}) => {
            return (
              <Space size={16}>
                <Popconfirm
                  title="删除任务"
                  description="确定要删除当前任务吗？"
                  okText="确定"
                  cancelText="取消"

                  onConfirm={() => {
                    return firstValueFrom(
                      IHttp.delManyPubTask(selectedRowKeys as number[]).pipe(
                        map(() => ref.current?.reload())
                      )
                    )
                  }}
                >
                  <a className="text-[#ff4d4f]">批量删除</a>
                </Popconfirm>
                <a onClick={() => {
                  setCutConfigTriggerId(selectedRowKeys as number[])
                }}>批量获取视频</a>
              </Space>
            );
          }}
          toolbar={{
            search: {
              onSearch: (value: string) => {
                alert(value);
              },
            },
            actions: [
              <Button type="primary" onClick={() => {
                setEditItem({id: 0})
              }}>添加</Button>,
              <Button type="primary" onClick={openGetVideoQueue}>查看队列</Button>
            ],
          }}
          rowKey="id"
          search={false}
        />
      </PageContainer>
      <PubTaskCreateForm
        item={editItem}
        onCancel={() => setEditItem(undefined)}
        onRefreshTable={() => {
          setEditItem(undefined)
          ref.current?.reload()
        }}
      />
      <VideoCutTemplateCreateForm
        item={cutConfigTriggerId.length > 0 ? {} as API.VideoCutTemplateItem : undefined}
        onCancel={() => setCutConfigTriggerId([])}
        mode='gettingVideoModal'
        onRefreshTable={() => {}}
        onFinish={data => {
          getTaskVideo(cutConfigTriggerId, JSON.parse(data.config))
          setCutConfigTriggerId([])
        }}
      />
      <PubAccountSelector
        item={pubAccountSelectorItem}
        onCancel={() => setPubAccountSelectorItem(undefined)}
        onRefreshTable={() => {
          setPubAccountSelectorItem(undefined)
          ref.current?.reload()
        }}
        onFinish={select_accounts => {
          return startPubTask(pubAccountSelectorItem as API.PubTaskItem, select_accounts)
        }}
      />
      <BatchAddForm
        item={batchAddItem}
        onCancel={() => setBatchAddItem(undefined)}
        onRefreshTable={() => {
          setBatchAddItem(undefined)
          ref.current?.reload()
        }}
      />
    </>
  )
}